package com.sna.snaapplication.service.UserSys.impl;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sna.snaapplication.entity.R;
import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.entity.usercore.UserRole;
import com.sna.snaapplication.mapper.RoleMapper;
import com.sna.snaapplication.mapper.UserMapper;
import com.sna.snaapplication.mapper.UserRoleMapper;
import com.sna.snaapplication.service.UserSys.AdminUserService;
import com.sna.snaapplication.service.UserSys.RoleService;
import com.sna.snaapplication.service.UserSys.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//是UserService接口的实现类
@Service
//把当前对象注册到ioc容器
public class AdminUserServiceImpl implements AdminUserService {
    //实现具体方法
    //需要调用mapper层方法执行sql查询 所以需要注入mapper对象
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;


    @Override
    public String validateUserInfo(User user) {
        StringBuilder errorMsg = new StringBuilder();
        if (user.getUserName() == null || user.getUserName().trim().isEmpty()) {
            errorMsg.append("登录账号不能为空; ");
        }
        if (user.getNickName() == null || user.getNickName().trim().isEmpty()) {
            errorMsg.append("用户昵称不能为空; ");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            errorMsg.append("登录密码不能为空; ");
        }
        if (user.getSex() == null || user.getSex().trim().isEmpty()) {
            errorMsg.append("用户性别不能为空; ");
        }
        return errorMsg.toString();
    }
    // 其他方法...

    @Override
    public R deleteUser(Long userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            return R.fail("用户不存在");
        }

        // 检查用户是否为管理员
        if ("admin".equals(roleMapper.FindByUserId(userId).getRoleKey())) {
            return R.fail("不能删除管理员用户");
        }

        // 删除用户
        int i=userRoleMapper.deleteById(userId);
        if(i==0){
            return R.fail("删除失败");
        }
        if(i>0){
            int result = userMapper.deleteById(userId);
            if (result > 0) {
                return R.ok("删除成功");
            }
        }
        return R.fail("删除失败");
    }
    @Override
    public R findUser(String userName,String phoneNumber,String status) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userName != null && !userName.isEmpty()) {
            queryWrapper.like("user_name",userName );
        }
        if (phoneNumber != null && !phoneNumber.isEmpty()) {
            queryWrapper.like("phonenumber", phoneNumber);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.like("status", status);
        }
        try {
            List<User> users = userMapper.selectList(queryWrapper);
            System.out.println(R.ok(users));
            return R.ok(users);
        } catch (Exception e) {
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @Override
    public R addUser(User user){
        User exitUser=userMapper.findByUserName(user.getUserName());
        if(exitUser==null) {
            //判断必填字段是否为空
            String errorMsg = validateUserInfo(user);
            if (!"".equals(errorMsg)) {
                return R.fail(errorMsg);
            }
            //必填字段不为空，则添加新用户

            //加密
            String password = user.getPassword();
            String encode = bCryptPasswordEncoder.encode(password);
            user.setPassword(encode);
            // 设置用户创建时间
            user.setCreateTime(new Date());

            int result = userMapper.insert(user);
            if (result > 0) {

                //用户的角色添加
                Long roleId = roleService.FindId("common");
                Long userId = user.getUserId();

                UserRole userRole = new UserRole();
                userRole.setUserId(userId).setRoleId(roleId);

                //插入用户角色user_role表中
                Integer num =userRoleService.saveUserRole(userRole);

                return R.ok("添加成功");
            }
            return R.fail("删除失败");
        }
        return R.fail("用户已存在，添加失败");
    }

    // 修改用户
    @Override
    public R modifyUser(User user) {
        // 检查用户是否存在
        User exitUser = userMapper.selectById(user.getUserId());
        if (exitUser == null) {
            return R.fail("用户不存在，修改失败");
        }

        // 获取要修改的用户的用户账号
        String userName = user.getUserName();
        if (userName != null && !userName.isEmpty()) {
            // 查询该用户名是否已被其他用户使用
            User exitUserName = userMapper.findByUserName(userName);
            if (exitUserName != null && !exitUserName.getUserId().equals(user.getUserId())) {
                return R.fail("该用户账号已被其他用户使用，修改失败");
            }
        }

        //用户信息更新时间
        user.setUpdateTime(new Date());
        // 更新用户信息
        int result = userMapper.updateById(user);

        if (result > 0) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }
}




